package com.itcs.se.security.tran;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxData;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.util.DateUtils;
import com.itcs.box.util.LogUtils;
import com.itcs.eureka.service.PayApiFeignClientService;
import com.itcs.se.security.data.req.Box1022Req;
import com.itcs.se.security.data.res.Box2022Res;
import com.itcs.se.security.service.SeSecurityService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @ClassName: BoxTranBJ1024
 * @Description:北京SE发行请求步骤2
 * @author: CHEN-HF
 * @date: 2018年10月20日 下午9:17:37
 * 
 * @Copyright: 2018 Inc. All rights reserved. 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
public class BoxTranModeWithB1024 implements PayApiFeignClientService {

	private Log logger = LogFactory.getLog(getClass());

	@Autowired
	private SeSecurityService seSecurityService;

	@Override
	public String getTrancode() {
		return "box_B1024";
	}

	@Override
	@RequestMapping(value = "/box_B1024", method = RequestMethod.POST, produces = "application/json")
	public Map<String, Object> exchange(String serverId, String trancode,
										@RequestParam Map<String, Object> reqRecord) {

		logger.info(LogUtils.build("B1024", "SE发行请求模式B", "上传数据:[" + JSON.toJSONString(reqRecord) + "]"));
		
		BoxResponse boxResponse = new BoxResponse();
		BoxData responseData = new BoxData();
		boxResponse.setData(responseData);

		Map<String, Object> res = new HashMap<>();
		try {
			BoxRequest boxRequest = (BoxRequest) reqRecord.get(BoxConstants.BOX_REQ_KEY);
			boxResponse = this.handle(boxRequest, boxResponse); // 业务处理
		} catch (Exception e) {
			responseData.setResult("9"); // 其他异常或数据库异常
		}
		res.put(BoxConstants.BOX_RES_KEY, boxResponse);

		return res;
	}

	public BoxResponse handle(BoxRequest boxRequest, BoxResponse boxResponse) {

		boxResponse.setMessgeType("2024"); // 消息类型

		BoxData data = boxRequest.getData();
		String deviceId = data.getDeviceId();
		BoxData responseData = new BoxData();

		Box1022Req req = new Box1022Req(data.getSeSn(), data.getSeR2());
		req.setClientId(deviceId);
		Box2022Res res = seSecurityService.doIssueRequest2ForBJ(req);

		responseData.setDeviceId(data.getDeviceId()); // 设备ID

		if (res.getErrCode().equals("0")) {
			responseData.setResult("1"); // 成功
			responseData.setSeWritePK(res.getSeWritePK()); // 写渠道公钥指令
		} else {
			responseData.setResult("9"); // 验证签名失败
		}
		responseData.setReplyTime(DateUtils.getUnixTimeStamp()); // 回复时间
		boxResponse.setData(responseData);

		return boxResponse;
	}

}
